// comm.hpp -- 用于描述管道文件的类和用于描述对管道文件操作的类
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
 
//设置为当前路径
#define PATH "."
#define NAME "fifo"
 
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    }while (0)



class namefifo
{
public:
    namefifo(const std::string path, const std::string name)
        : _path(path)
        , _name(name)
    {
        // 创建管道文件
        _filename = _path + "/" + _name;
        umask(0);
        int n = mkfifo(_filename.c_str(), 0664);
        if (n < 0)
            ERR_EXIT("mkfifo");
        else
        {
            std::cout << "mkfifo success" << std::endl;
        }
    }

     ~namefifo()
    {
        int n = unlink(_filename.c_str());
        // 删除成功
        if (n == 0)
        {
            ERR_EXIT("unlink");
        }
        else    // 删除失败
        {
            std::cout << "remove fifo failed" << std::endl;
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _filename;
};
    


class namefile
{
public:
    namefile(const std::string path, const std::string name)
        : _path(path)
        , _name(name)
        , _fd(-1)
    {
        _filename = _path + "/" + _name;
    }

    void OpenForRead()
    {
        _fd = open(_filename.c_str(), O_RDONLY);
        if (_fd < 0)
            ERR_EXIT("open");
        else if (_fd > 0)
        {
            std::cout << "open success" << std::endl;
        }
        else
        {}
    }

    void OpenForWrite()
    {
        _fd = open(_filename.c_str(), O_WRONLY);
        if (_fd < 0)
            ERR_EXIT("open");
        else if (_fd > 0)
        {
            std::cout << "open success" << std::endl;
        }
        else
        {}
    }

    //  服务端进行读
    void Read()
    {
        char buf[1024];
        int n;
        while (true)
        {
            n = read(_fd, buf, sizeof(buf) - 1);
            buf[n] = 0;
            if (n > 0)
            {
                std::cout << "Client say # " << buf << std::endl;
            }
            else if (n == 0)
            {
                std::cout << "Client quit! me too !" << std::endl;
                break;
            }
            else
            {
                // TODO
            }
        }
    }

    //  客户端进行写
    void Write()
    {
        std::string message;
        while (true)
        {
            std::cin >> message;
            int n = 0;
            write(_fd, message.c_str(), message.size());
        }
    }
    void Close()
    {
        close(_fd);
    }


private:
    std::string _path;
    std::string _name;
    std::string _filename;
    int _fd;
};
